import React, { useEffect } from "react";
// import { useNavigate } from "react-router-dom";

import * as d3 from "d3";
import { VbpStatsByCadnI } from "../../../types";

interface PropsI {
  data: VbpStatsByCadnI[];
  watermarkText?: string;
  statsStartDate?: Date;
  statsEndDate?: Date;
  selectedBatch?: string;
}

const GroupBarChartByCadn: React.FC<PropsI> = (props) => {
  const {
    data,
    watermarkText = "",
    statsStartDate,
    statsEndDate,
    selectedBatch = "%",
  } = props;
  const refChart = React.useRef(null);

  useEffect(() => {
    const filteredData = data.filter(
      (item: VbpStatsByCadnI) => item.percent >= 0
    );
    if (
      refChart &&
      refChart.current &&
      filteredData &&
      filteredData.length > 0
    ) {
      const node = refChart.current;

      // 使用d3.rollup()汇总数据
      const aggregatedData = d3.rollup(
        filteredData,
        (
          group // 对应每个分组的数据
        ) =>
          d3.sum(group, (d) => {
            // console.log(group);
            return d.percent;
          }),
        (d) => d.cadn + "-" + d.monitorClass, // 分级汇总，先按cadn，后按vbpClass
        (d) => d.vbpClass
      );

      // 使用迭代器来排序
      function sortMapEntries(map: any, compareFn: any) {
        const entries = [...map.entries()];
        const sortedEntries = entries.sort(compareFn);
        return new Map(sortedEntries);
      }
      // 对Map的条目进行排序
      const sortedAggregatedData = sortMapEntries(
        aggregatedData,
        (a: any, b: any) => {
          if (a[1].get("中选") >= b[1].get("中选")) {
            return 1;
          } else {
            return -1;
          }
        }
      );

      const vbpClasses = new Set(
        filteredData.map((d: VbpStatsByCadnI) => d.vbpClass)
      );
      // 设定svg元素所占面积
      const margin = { top: 50, right: 130, bottom: 30, left: 380 };
      var rectStep = 45;
      const width = 1280;
      const height =
        rectStep * sortedAggregatedData.size * vbpClasses.size +
        margin.top +
        margin.bottom;
      // 设定四周边距

      d3.select(node).selectAll("svg").remove();
      var svg = d3
        .select(node)
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("viewBox", [0, 0, width, height]) // 后续rect等图是相对viewBox计算的，viewBox可随svg绽放
        .attr("style", "max-width: 100%; height: auto;");
      // .attr("transform", `translate(${margin.left}, ${margin.top})`); // svg元素相对父节点元素位置

      const xScale = d3
        .scaleLinear()
        .domain([
          0,
          d3.max(sortedAggregatedData, (D: any) => {
            // console.log(D);
            return d3.max(D[1], (d: any) => {
              // console.log(d);
              return d[1];
            });
          }) as any,
        ])
        .range([0, width - margin.left - margin.right]);

      // 获取Map的key
      const keys = [...sortedAggregatedData.entries()].map((item) => {
        // console.log(item);
        return item[0];
      });

      // console.log(keys);
      // console.log(new Set(keys));
      // 控制不同组的排序
      const yCadnScale = d3
        .scaleBand()
        .domain(keys as any)
        .rangeRound([0, height - margin.top - margin.bottom])
        .paddingInner(0.2);

      // console.log(yCadnScale.bandwidth());

      // console.log(d3.schemeSpectral[3]); // 至少3种颜色，最多11种
      const colorScale = d3
        .scaleOrdinal()
        .domain(vbpClasses)
        // .range(d3.schemeSpectral[11]);
        .range(["green", "orange", "blue"]);
      // console.log(colorScale("中选"));
      // console.log(colorScale("其他"));
      // console.log(colorScale("原研"));
      // console.log(vbpClasses);

      const yVbpScale = d3
        .scaleBand()
        .domain(vbpClasses)
        .rangeRound([0, yCadnScale.bandwidth()])
        .paddingInner(0.1);

      // console.log(yVbpScale.bandwidth());

      // 添加 x 轴
      svg
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`)
        .call(
          d3
            .axisTop(xScale)
            .tickSize(1)
            .tickFormat((d: any) => `${(d * 100).toFixed(0)}%`)
        );

      // 添加 y 轴
      svg
        .append("g")
        .attr("class", "yAxis")
        .attr("transform", `translate(${margin.left},${margin.top})`)
        .call(d3.axisLeft(yVbpScale).tickSize(0))
        .selectAll(".domain")
        .remove();

      svg.selectAll(".yAxis").selectAll("text").remove();

      // 添加坐标轴标签
      svg
        .append("text")
        .attr("class", "x-label")
        .attr("text-anchor", "end")
        .attr("x", margin.left + (width - margin.left - margin.right) / 2) // 横坐标标签居中
        .attr("y", 20) // 位于 x 轴下方
        .text("比例");

      svg
        .append("text")
        .attr("class", "y-label")
        .attr("text-anchor", "middle")
        .attr("transform", "rotate(-90)") // 旋转 90 度；旋转后x, y属性也受影响
        .attr("x", -(margin.top + (height - margin.top - margin.bottom) / 2)) // 横坐标标签居中
        .attr("y", 30) // 向上偏移
        .text("药品类别");

      // 画柱状图
      const bars = svg
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`) // 相对svg元素
        .selectAll(".cadnBar")
        .data(sortedAggregatedData)
        .join("g")
        .attr("class", "cadnBar")
        .attr("transform", (D: any) => {
          // console.log(D);
          // console.log(yCadnScale(D[0]));
          return `translate(0, ${yCadnScale(D[0])})`;
        }) // 每组通用名的柱状图偏移
        .selectAll(".groupBar") // 添加一个分组层为了转换数据
        .data((D: any) => {
          // console.log(D);
          // console.log(D[1]);
          // 为了将通用名和集采类别参数传入下级，支持点击柱子时传参下钻查询
          const subData: any = [];
          D[1].forEach((value: any, key: any) => {
            subData.push({
              key: key,
              value: value,
              cadn: D[0],
            });
          });
          return subData;
        })
        .join("g")
        .attr("class", "groupBar")
        .append("rect")
        .attr("x", 0)
        .attr("y", (d: any) => {
          // console.log(d);
          // console.log(yVbpScale(d.key));
          return yVbpScale(d.key) as any;
        })
        .attr("width", (d: any) => {
          // console.log(d);
          // console.log(yVbpScale(d.key));
          return xScale(d.value) as any;
        })
        .attr("height", yVbpScale.bandwidth())
        .attr("fill", (d: any) => {
          // console.log(d);
          return colorScale(d.key) as any;
        });

      bars.on("click", (event, d: any) => {
        // console.log(d);
        // console.log(statsStartDate);
        // console.log(statsEndDate);
        const url = new URL("/vbp/cadn-vbp-d3", window.location.origin);
        const result = d.cadn.split("-");
        url.searchParams.set("cadn", JSON.stringify(result[0])); // 参数统一使用JSON编码，后端统一用JSON解码（双引号）
        url.searchParams.set("vbpClass", JSON.stringify(d.key));
        url.searchParams.set("monitorClass", JSON.stringify(result[1]));
        url.searchParams.set("startDate", JSON.stringify(statsStartDate));
        url.searchParams.set("endDate", JSON.stringify(statsEndDate));
        url.searchParams.set("batchEndDate", JSON.stringify(selectedBatch));
        window.open(url.toString(), "_blank");
      });

      // 添加鼠标悬停事件
      bars.on("mouseover", function (event, d) {
        // 改变颜色或其他样式
        d3.select(this).attr("cursor", "pointer");
      });

      // 添加分组标签;
      svg
        .selectAll(".groupLabel")
        .data(sortedAggregatedData)
        .join("text")
        .attr("class", "groupLabel")
        .attr("transform", `translate(0,${margin.top})`) // 相对svg元素
        .attr("font-weight", "normal")
        .attr("font-size", 12)
        .attr("x", 60)
        .attr("y", (D: any) => yCadnScale(D[0])! + yCadnScale.bandwidth() / 2)
        .attr("dy", "0.35em")
        .text((D: any) => D[0]); // 画完分组标签

      // 添加柱子对应的值标签
      svg
        .selectAll(".group")
        .data(aggregatedData)
        .join("g")
        .attr("class", "group")
        .attr(
          "transform",
          (D) => `translate(0, ${margin.top + yCadnScale(D[0])!})`
        )
        .selectAll(".label")
        .data(([, d]) => d)
        .join("text")
        .attr("transform", `translate(${margin.left + 6}, 0)`) // 相对svg元素
        .attr("font-weight", "normal")
        .attr("font-size", 12)
        .attr("x", (d) => {
          // console.log(d);
          return xScale(d[1]);
        })
        .attr("y", (d) => {
          return yVbpScale(d[0])! + yVbpScale.bandwidth() / 2;
        })
        .attr("dy", "0.5em")
        .attr("text-anchor", "start")
        .text((d) => {
          return d[0] + " " + (d[1] * 100).toFixed(2) + "%";
        });

      // 添加图例
      const legend = svg
        .selectAll(".legend")
        .data(vbpClasses)
        .join("g")
        .attr("class", "legend")
        .attr("transform", (d, i) => `translate(0,${i * 20 + 20})`);

      legend
        .append("rect")
        .attr("x", 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", colorScale as any);

      legend
        .append("text")
        .attr("x", 76)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text((d: any) => {
          // console.log(d);
          return d;
        });

      // 添加100％达标线
      svg
        .append("line")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .attr("x1", xScale(1))
        .attr("y1", 0)
        .attr("x2", xScale(1))
        .attr("y2", height - margin.top - margin.bottom)
        .attr("stroke", "green")
        .attr("stroke-width", 1);

      // 添加水印
      // const watermark = svg.append("g").attr("class", "watermark");
      // const watermarkSize = 400;
      // const columns = Math.ceil(width / watermarkSize);
      // const rows = Math.ceil((height / watermarkSize) * 2);
      // // 生成水印
      // for (let i = 0; i < rows; i++) {
      //   for (let j = 0; j < columns; j++) {
      //     watermark
      //       .append("text")
      //       .attr("x", j * watermarkSize)
      //       .attr("y", (i * watermarkSize) / 2)
      //       .attr("font-size", "4rem")
      //       .attr("fill", "rgba(0, 0, 0, 0.1)")
      //       // .attr("transform", "rotate(-45)")
      //       .text(watermarkText);
      //   }
      // }
    }

    // 清除副作用
    return () => {
      d3.select(refChart.current).selectAll("*").remove();
    };
  }, [data]);

  return (
    <div>
      <div ref={refChart}></div>
    </div>
  );
};

export default GroupBarChartByCadn;
